#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMessageBox>
#include <QFont>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    , m_pet(new Pet(this))
    , m_timeManager(new TimeManager(this))
    // 初始化
    , clickCount(0)
    , progressValue(0)
    , isBathFinish(false)
{
    ui->setupUi(this);

    // 连接信号与槽
    connect(ui->startButton, &QPushButton::clicked, this, &MainWindow::startButtonClick);
    connect(ui->confirmButton, &QPushButton::clicked, this, &MainWindow::confirmButtonClick);
    connect(m_timeManager, &TimeManager::timeTick, this, &MainWindow::timeTick);

    connect(ui->feedButton, &QPushButton::clicked, this, &MainWindow::feedButtonClick);
    connect(ui->cleanButton, &QPushButton::clicked, this, &MainWindow::cleanButtonClick);
    connect(ui->playButton, &QPushButton::clicked, this, &MainWindow::playButtonClick);

    // 更新
    connect(m_pet, &Pet::statusChange, this, &MainWindow::updateStatus);
    connect(m_pet, &Pet::levelUpSignal, this, &MainWindow::petLevelUp);
    connect(m_pet, &Pet::statusChange, this, &MainWindow::updatePetImage);

    // 吃
    connect(ui->cakeButton, &QPushButton::clicked, this, &MainWindow::cakeButtonClick);
    connect(ui->hambButton, &QPushButton::clicked, this, &MainWindow::hambButtonClick);
    connect(ui->eggButton, &QPushButton::clicked, this, &MainWindow::eggButtonClick);

    // 玩耍
    connect(ui->singButton, &QPushButton::clicked, this, &MainWindow::singButtonClick);
    connect(ui->layButton, &QPushButton::clicked, this, &MainWindow::layButtonClick);
    connect(ui->celebrateButton, &QPushButton::clicked, this, &MainWindow::celebrateButtonClick);

    connect(ui->continueButton, &QPushButton::clicked, this, &MainWindow::levelUpButtonClick);
    connect(ui->exitButton, &QPushButton::clicked, this, &MainWindow::exitButtonClick);
    connect(ui->replayButton, &QPushButton::clicked, this, &MainWindow::replayButtonClick);
    connect(ui->exitButton2, &QPushButton::clicked, this, &MainWindow::exitButtonClick);
    connect(ui->replayButton2, &QPushButton::clicked, this, &MainWindow::replayButtonClick);
    connect(m_pet, &Pet::gameOver, this, &MainWindow::gameIsOver);


    // 起始页面的显示
    ui->stackedWidget->setCurrentWidget(ui->startPage);
    updateStatus();

    // 设置格式
    ui->cakeButton->setStyleSheet("QPushButton { icon-size: 70px 70px; }");
    ui->hambButton->setStyleSheet("QPushButton { icon-size: 70px 70px; }");
    ui->eggButton->setStyleSheet("QPushButton { icon-size: 70px 70px; }");

    ui->singButton->setStyleSheet("QPushButton { icon-size: 70px 70px; }");
    ui->layButton->setStyleSheet("QPushButton { icon-size: 70px 70px; }");
    ui->celebrateButton->setStyleSheet("QPushButton { icon-size: 70px 70px; }");

    // 洗澡跟踪
    setMouseTracking(true);

    ui->petImageLabel->setScaledContents(true);
    ui->feedButton->setEnabled(false);
    ui->cleanButton->setEnabled(false);
    ui->playButton->setEnabled(false);

    ui->feedPetLabel->setScaledContents(true);
    ui->playPetLabel->setScaledContents(true);
    ui->cleanPetLabel->setScaledContents(true);

    foodDialog << "小主人，我想吃蛋糕！" << "小主人，我想吃汉堡！" << "小主人，我想吃鸡蛋！";
    playDialog << "小主人，我想唱歌！" << "小主人，我想休息了~" << "小主人，我想庆祝！";
}

MainWindow::~MainWindow()
{
    delete ui;
    delete m_pet;
    delete m_timeManager;
}

void MainWindow::startButtonClick()
{
    ui->stackedWidget->setCurrentWidget(ui->namePage);
}

void MainWindow::timeTick()
{
    m_pet->deHunger();
    m_pet->deClean();
    m_pet->dePleasure();
    updateStatus();
}

void MainWindow::confirmButtonClick()
{
    QString petName = ui->nameLine->text();
    if (!petName.isEmpty())
    {
        m_pet->setName(petName);
        ui->stackedWidget->setCurrentWidget(ui->gamePage);

        ui->feedButton->setEnabled(true);
        ui->cleanButton->setEnabled(true);
        ui->playButton->setEnabled(true);

        m_timeManager->start();

        updateStatus();
    }
}

void MainWindow::feedButtonClick()
{
    ui->sceneStackedWidget->setCurrentWidget(ui->feedPage);
    ui->feedPetLabel->setPixmap(QPixmap(":/images/full.png"));
    showRandomDialog();
    randomButtonLayout(ui->feedPage);
}

void MainWindow::cleanButtonClick()
{
    ui->sceneStackedWidget->setCurrentWidget(ui->cleanPage);
    ui->cleanPetLabel->setPixmap(QPixmap(":/images/sad.png"));
}

void MainWindow::playButtonClick()
{
    ui->sceneStackedWidget->setCurrentWidget(ui->playPage);
    ui->playPetLabel->setPixmap(QPixmap(":/images/normal.png"));
    showRandomPlayDialog();
    randomButtonLayout(ui->playPage);
}

void MainWindow::backToMainButton()
{
    ui->sceneStackedWidget->setCurrentWidget(ui->dayPage);
}


void MainWindow::cakeButtonClick()
{
    handleFoodDrop("蛋糕");
}

void MainWindow::hambButtonClick()
{
    handleFoodDrop("汉堡");
}

void MainWindow::eggButtonClick()
{
    handleFoodDrop("鸡蛋");
}

void MainWindow::showRandomDialog()
{
    int index = QRandomGenerator::global()->generate() % foodDialog.size();
    QString dialogue = foodDialog.at(index);
    ui->dialogLabel->setText(dialogue);
}

void MainWindow::handleFoodDrop(const QString &food)
{
    QString dialogue = ui->dialogLabel->text();
    if (dialogue.contains(food))
    {
        ui->feedPetLabel->setPixmap(QPixmap(":/images/full.png"));
        QTimer::singleShot(1000, [this]()
        {
            m_pet->inHunger(30);
            ui->sceneStackedWidget->setCurrentWidget(ui->dayPage);
        });
    }
    else
    {
        ui->feedPetLabel->setPixmap(QPixmap(":/images/wrong.png"));
        randomButtonLayout(ui->feedPage);
        QTimer::singleShot(1000, [this]()
        {
            showRandomDialog();
            ui->feedPetLabel->setPixmap(QPixmap(":/images/full.png"));
        });
    }
}



void MainWindow::mousePressEvent(QMouseEvent *event) //洗澡进度条
{
    if (ui->cleanPetLabel->geometry().contains(event->pos()))
    {
        if (isBathFinish)
        {
            clickCount = 0;
            isBathFinish = false;
        }
        clickCount++;
        progressValue = clickCount * 10;
        ui->progressBar->setValue(progressValue);

        if (progressValue >= 60 && progressValue < 80)
        {
            ui->cleanPetLabel->setPixmap(QPixmap(":/images/shower.png"));
        }
        else if (progressValue >= 80)
        {
            ui->cleanPetLabel->setPixmap(QPixmap(":/images/wind.png"));
        }

        if (progressValue >= 100)
        {
            progressValue = 100;
            ui->progressBar->setValue(progressValue);
            // 返回主页面并增加血条
            QTimer::singleShot(1000, [this]()
            {
                m_pet->inClean(25);
                ui->sceneStackedWidget->setCurrentWidget(ui->dayPage);
            });
            progressValue = 0;
            isBathFinish = true;
        }
    }
}



void MainWindow::singButtonClick()
{
    handlePlayAction("唱歌");
}

void MainWindow::layButtonClick()
{
    handlePlayAction("休息");
}

void MainWindow::celebrateButtonClick()
{
    handlePlayAction("庆祝");
}

void MainWindow::showRandomPlayDialog()
{
    int index = QRandomGenerator::global()->generate() % playDialog.size();
    QString dialogue = playDialog.at(index);
    ui->playDialogLabel->setText(dialogue);
}

void MainWindow::handlePlayAction(const QString &action)
{
    QString dialogue = ui->playDialogLabel->text();
    if (dialogue.contains(action))
    {
        if (action == "唱歌")
        {
            ui->playPetLabel->setPixmap(QPixmap(":/images/sing.png"));
        }
        else if (action == "休息")
        {
            ui->playPetLabel->setPixmap(QPixmap(":/images/lay.png"));
        }
        else if (action == "庆祝")
        {
            ui->playPetLabel->setPixmap(QPixmap(":/images/celebrate.png"));
        }
        // 返回主页面并增加血条
        QTimer::singleShot(1000, [this]()
        {
            m_pet->inPleasure(20);
            ui->sceneStackedWidget->setCurrentWidget(ui->dayPage);
        });
    }
    else
    {
        ui->playPetLabel->setPixmap(QPixmap(":/images/wrong.png"));
        randomButtonLayout(ui->playPage);
        // 选错 随机生成新需求
        QTimer::singleShot(1000, [this]()
        {
            showRandomPlayDialog();
            ui->playPetLabel->setPixmap(QPixmap(":/images/normal.png"));
        });
    }
}

void MainWindow::levelUpButtonClick()
{

    ui->stackedWidget->setCurrentWidget(ui->gamePage);

}

void MainWindow::petLevelUp(int level)
{
    ui->petLabel->setText(QString("宠物: %1 \n(等级: %2)").arg(m_pet->getName()).arg(level));
    ui->levelUpLabel->setText(QString("宠物升到%1级了！").arg(level));
    ui->stackedWidget->setCurrentWidget(ui->levelUpPage);
}

void MainWindow::gameIsOver()
{
    QString gameClearedText = "恭喜你，宠物达到最高等级，游戏通关！\n \n小狗想说：谢谢你把我照顾得这么好！ \n \n我在外面找到了很好的伙伴，不用担心我噢！";
    ui->gameClearedLabel->setText(gameClearedText);
    ui->feedButton->setEnabled(false);
    ui->cleanButton->setEnabled(false);
    ui->playButton->setEnabled(false);
    ui->stackedWidget->setCurrentWidget(ui->gameClearedPage);
}

void MainWindow::updatePetImage()
{
    QString imagePath = m_pet->getStatusImage();
    ui->petImageLabel->setPixmap(QPixmap(imagePath));
}

void MainWindow::updateStatus()
{
    ui->petLabel->setText(QString("宠物: %1 \n(等级: %2)").arg(m_pet->getName()).arg(m_pet->getLevel()));

    ui->hungerBar->setValue(m_pet->getHunger());
    ui->cleanBar->setValue(m_pet->getClean());
    ui->pleasureBar->setValue(m_pet->getPleasure());

    updatePetImage();

    if (!m_pet->isAlive())
    {
        QString petDeadText = " 游戏结束！ \n \n 你的宠物去汪星了...";
        ui->petDeadLabel->setText(petDeadText);
        ui->feedButton->setEnabled(false);
        ui->cleanButton->setEnabled(false);
        ui->playButton->setEnabled(false);
        ui->stackedWidget->setCurrentWidget(ui->petDeadPage);
    }
}

void MainWindow::exitButtonClick()
{
    qApp->quit();
}

void MainWindow::replayButtonClick()
{
    // 重置各种状态
    m_pet->reset();

    ui->stackedWidget->setCurrentWidget(ui->startPage);
    ui->feedButton->setEnabled(false);
    ui->cleanButton->setEnabled(false);
    ui->playButton->setEnabled(false);
    ui->nameLine->clear();

    clickCount = 0;
    progressValue = 0;
    isBathFinish = false;

    ui->hungerBar->setValue(m_pet->getHunger());
    ui->cleanBar->setValue(m_pet->getClean());
    ui->pleasureBar->setValue(m_pet->getPleasure());
    ui->petLabel->setText(QString("宠物: %1 \n(等级: %2)").arg(m_pet->getName()).arg(m_pet->getLevel()));
    ui->gameClearedLabel->clear();
    ui->petDeadLabel->clear();
}


void MainWindow::randomButtonLayout(QWidget *pageWidget)
{
    QPushButton *cakeButton = ui->cakeButton;
    QPushButton *hambButton = ui->hambButton;
    QPushButton *eggButton = ui->eggButton;

    QPushButton *celebrateButton = ui->celebrateButton;
    QPushButton *singButton = ui->singButton;
    QPushButton *layButton = ui->layButton;

    // 获取页面的宽度、高度
    int pageWidth = pageWidget->width();
    int pageHeight = pageWidget->height();

    int feedVerticalOffset = 80;
    int feedHorizontalOffset = -20;

    int playVerticalOffset = 30;
    int playHorizontalOffset = 0;

    // 按钮间距
    int buttonSpacing = 10;

    // 计算喂食按钮位置
    int feedButtonWidth = cakeButton->width();
    int feedButtonHeight = cakeButton->height();
    int feedX = (pageWidth - 3 * feedButtonWidth - 2 * buttonSpacing) / 2 + feedHorizontalOffset;
    int feedY = pageHeight - feedButtonHeight - 10 - feedVerticalOffset;

    // 随机排列喂按钮
    QList<QPushButton*> feedButtons = {cakeButton, hambButton, eggButton};
    std::random_shuffle(feedButtons.begin(), feedButtons.end());
    for (int i = 0; i < feedButtons.size(); ++i)
    {
        feedButtons[i]->move(feedX + i * (feedButtonWidth + buttonSpacing), feedY);
    }

    // 计算玩耍按钮位置
    int playButtonWidth = celebrateButton->width();
    int playButtonHeight = celebrateButton->height();
    int playX = (pageWidth - 3 * playButtonWidth - 2 * buttonSpacing) / 2 + playHorizontalOffset;
    int playY = pageHeight - playButtonHeight - 10 - playVerticalOffset;

    // 随机排列玩耍按钮
    QList<QPushButton*> playButtons = {celebrateButton, singButton, layButton};
    std::random_shuffle(playButtons.begin(), playButtons.end());
    for (int i = 0; i < playButtons.size(); ++i)
    {
        playButtons[i]->move(playX + i * (playButtonWidth + buttonSpacing), playY);
    }
}
